package com.kvn.universal.core;

import com.kvn.universal.core.idempotent.IdempotentContext;
import com.kvn.universal.core.lock.LockContext;
import com.kvn.universal.core.lock.LockHolder;
import com.kvn.universal.dao.IIdempotentDao;
import com.kvn.universal.filter.Callback;
import com.kvn.universal.filter.Filter;
import com.kvn.universal.filter.FilterFactory;
import com.kvn.universal.filter.idempotent.IdempotentHolder;

/**
 * @author wzy
 * @date 2017年8月2日 下午5:20:14
 */
public class BizService implements Invoker {
	private IIdempotentDao idempotentDao;

	public BizService(IIdempotentDao idempotentDao) {
		super();
		this.idempotentDao = idempotentDao;
	}

	public String doBiz(String param) {
		InvokerContext context = InvokerContext.create().apendArg(param);
		context.putExtendContext(LockContext.create().appendLock(LockHolder.create("wzy", null)));
		context.putExtendContext(IdempotentContext.create(IdempotentHolder.create("我是幂等key-10", "33", "23")));
		String rlt = (String) InvokerBuilder
				.buildInvoker(this, context, FilterFactory.createIdempodentFilter(idempotentDao), FilterFactory.createLockFilter())
				.delegateInvokeInvoker();
		System.out.println("==>执行结果：" + rlt);
		return rlt;
	}
	
	/**
	 * 测试幂等，使用 callback 返回幂等结果
	 * @param param
	 * @return
	 */
	public String doBizUseCallbackIdempotent(String param){
		InvokerContext context = InvokerContext.create().apendArg(param);
		context.putExtendContext(LockContext.create().appendLock(LockHolder.create("wzy", null)));
		context.putExtendContext(IdempotentContext.create(IdempotentHolder.create("我是幂等key-11", "11", "22")));
		Filter IdempodentFilter = FilterFactory.createIdempodentFilter(idempotentDao, new Callback() {
			@Override
			public Object call(InvokerContext context) {
				return "callback返回的幂等结果";
			}
		});
		String rlt = (String) InvokerBuilder
				.buildInvoker(this, context, IdempodentFilter, FilterFactory.createLockFilter())
				.delegateInvokeInvoker();
		System.out.println("==>执行结果：" + rlt);
		return rlt;
	}
	
	@Override
	public Object invoke(InvokerContext lockContext) {
		String param = (String) lockContext.getArgs().get(0);
		System.out.println("---> 执行业务:param=" + param);
		return "OK";
	}
}
